import { Space, Table, Tag , Button } from 'antd';
import React, { useState,useEffect } from 'react';
import axios from "../../utils/axios"
import Delmodal from '../../components/delmodal';
import Addeditmodal  from '../../components/addeditmodal';
const App = () => {
    let [arr,setArr] = useState([])
    let [ismodelopen,setIsmodelopen] = useState(false)
    let [addismodelopen,setaddIsmodelopen] = useState(false)
    let [delIndex,setDelINDEX] = useState(0)
    let [editIndex,setEditINDEX] = useState(0)
    let [edititem,setedititem] = useState({})
    let [isadd,setIsadd] = useState("新增")
    let [colums,setColums] = useState([
      {
        title: 'Name',
        dataIndex: 'name',
        key: 'name',
        render: (text) => <a>{text}</a>,
      },
      {
        title: 'sex',
        dataIndex: 'sex',
        key: 'sex',
      },
      {
        title: 'Address',
        dataIndex: 'address',
        key: 'address',
      },
      {
        title: '操作',
        key: 'action',
        render: (_, record,index) => (
          <Space size="middle">
            <a onClick={()=>editfn(record,index)}>编辑</a>
            <a onClick={()=>delfn(index)}>Delete</a>
          </Space>
        ),
      },
    ]

    )
    let editfn = (item,index)=>{
      console.log(item,index);
      setEditINDEX(index)
      setedititem(item)
      setIsadd("编辑")
      setaddIsmodelopen(true)
    }
    let modelclose = (data)=> { // 新增弹窗关闭的方法
        console.log(data)
        if (isadd === "新增") {
          if (data.values) { // 说明要新增
            let newArr = [...arr]
            newArr.unshift(data.values)
            setArr(newArr)
          }
        } else {
          let newaRR = [...arr]
          newaRR.splice(editIndex,1,data.values)
          setArr(newaRR)
        }
       
        setaddIsmodelopen(data.close)
    }
    let delfn = (index)=>{ // 删除的函数
      console.log(index);
      setDelINDEX(index)
      setIsmodelopen(true)
    }
    let addfn = ()=> { // 新增的函数
      setaddIsmodelopen(true)
      setIsadd("新增")
    }
    let delsurefn = (data)=>{ //用于接收父组件给子组件传递参数
      setIsmodelopen(data.sure)
      if (data.isok === "确定") {
         let neearr = [...arr]
         neearr.splice(delIndex,1)
         setArr(neearr)

      }
    }
    useEffect(()=>{
      axios.get("/api/tablelist").then(res=>{
        setArr(res.data)
      })
    },[])

    return (
      // 空标签是React.Fragment的简写
      <React.Fragment>
        <Button onClick={addfn}>新增</Button>
        <Table columns={colums} dataSource={arr} />
        <Delmodal ismodelopen = {ismodelopen} delsurefn = {delsurefn}></Delmodal>
         {/* 告诉子组件要编辑第几条，编辑回显，是做新增还是编辑 */}
        <Addeditmodal ismodelopen={addismodelopen} modelclose = {modelclose} editIndex={editIndex} edititem={edititem} isadd={isadd}></Addeditmodal>
      </React.Fragment>
    ) 

};
export default App;